package com.mmp.main.endpoints;

import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.mmp.common.util.Common;
import com.mmp.main.servlet.joborder.JobOrderNotificationsEmitter;

@ServerEndpoint("/JobOrdersNotifier")
public class JobOrderNotificationsEndPoint {

	private static final Logger LOGGER = Logger.getLogger(JobOrderNotificationsEndPoint.class.getName());
	private static Queue<Session> queue = new ConcurrentLinkedQueue<>();

	@OnOpen
	public void onOpen(Session session) {
		queue.add(session);
		//sendMessage(session, "");
		LOGGER.log(Level.INFO, "New connection with client: {0}", session.getId());
		Common.log("Number of opened connections is ************** " + queue.size());
	}

	@OnClose
	public void onClose(Session session) {
		queue.remove(session);
		LOGGER.log(Level.INFO, "Close connection for client: {0}", session.getId());
		Common.log("Number of opened connections is ************** " + queue.size());
	}

	@OnError
	public void onError(Throwable exception, Session session) {
		queue.remove(session);
		exception.printStackTrace();
		LOGGER.log(Level.INFO, "Error for client: {0}", session.getId());
	}

/*	@OnMessage
	public String onMessage(String message, Session session) {
		try {
			session.getBasicRemote().sendText("hello world ! notifications websocket works fine");
		} catch (IOException e) {
			Common.log(e);
		}
		return "Server received [" + message + "]";
	}*/

	public static void sendMessageToAll(String message) {
		try {
			for (Session s : queue) {
				sendMessage(s, message);
				LOGGER.log(Level.INFO, "Sent:" + s.getId(), message);
			}
		} catch (Exception e) {
			Common.log(e);
		}

	}

	private static void sendMessage(Session session, String msg) {
		try {
			if (session != null && session.isOpen())
				session.getBasicRemote().sendText(msg);
		} catch (IOException e) {
			Common.log(e);
		}
	}

}
